package com.icinfo.cloud.provider.common.utils;

import com.icinfo.cloud.provider.common.annotation.CheckTime;
import org.springframework.util.ObjectUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.SimpleDateFormat;

/**
 * 描述：时间校验器
 *
 * @author xiangyuyu
 * @date 2022-02-22 18:34
 */
public class TimeValidator implements ConstraintValidator<CheckTime, String> {

    private String format;

    @Override
    public void initialize(CheckTime constraintAnnotation) {
        this.format = constraintAnnotation.format();
    }

    @Override
    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {

        return validator(object, format);
    }

    static boolean validator(String object, String format2) {
        if (ObjectUtils.isEmpty(object)) {
            return true;
        }
        String pattern = format2;
        boolean isValid = true;
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try {
            format.setLenient(false);
            format.parse(object);
        } catch (Exception ex) {
            isValid = false;
        }
        return isValid;
    }


}